/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年9月25日
 */
package com.massyframework.beanskin.runtime.framework.installing;

import java.io.IOException;
import java.net.URL;

import org.xml.sax.SAXException;

import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;

/**
 * Json解析器
 * @author huangkh
 *
 */
public abstract class JsonParser {

	/**
	 * 
	 */
	public JsonParser() {
	}

	/**
	 * 验证{@code data}的有效性
	 * @param data {@link JsonNode}
	 * @throws SAXException 
	 * @throws IOException
	 * @throws ProcessingException 
	 */
	protected void validateJson(JsonNode data, URL schemaUrl) 
			throws SAXException, IOException, ProcessingException{
		JsonSchema schema = this.loadJsonSchemaFromUrl(schemaUrl);
		schema.validate(data);
	}
	
	/**
	 * 从{@code url}中加载JsonSchema
	 * @return {@link JsonSchema}
	 * @throws IOException 
	 * @throws ProcessingException 
	 */
	protected JsonSchema loadJsonSchemaFromUrl(URL schemaUrl) 
			throws IOException, ProcessingException {		
		//创建JsonSchema工厂
		JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
		//通过jsonSchema获得对应JsonNode对象
		JsonNode schemaNode =  JsonLoader.fromURL(schemaUrl);
		return factory.getJsonSchema(schemaNode);
	}
	
	/**
	 * 通过{@code url}加载json数据
	 * @param url {@link URL},路经
	 * @return {@link  JsonNode}
	 * @throws IOException
	 */
	protected JsonNode loadJsonNode(URL url) throws IOException {
		//通过jsonSchema获得对应JsonNode对象
		return JsonLoader.fromURL(url);
	}
}
